package cn.zzdt4j.config.controller;

import cn.hutool.core.util.StrUtil;
import cn.zzdt4j.common.constant.ConfigModifyTypeConstants;
import cn.zzdt4j.common.constant.Constants;
import cn.zzdt4j.common.model.Result;
import cn.zzdt4j.common.toolkit.BeanUtil;
import cn.zzdt4j.common.toolkit.UserContext;
import cn.zzdt4j.config.model.ConfigAllInfo;
import cn.zzdt4j.config.model.ConfigInfoBase;
import cn.zzdt4j.config.model.biz.threadpool.ConfigModifySaveReqDTO;
import cn.zzdt4j.config.service.biz.ConfigService;
import cn.zzdt4j.config.verify.ConfigModificationVerifyServiceChoose;
import cn.zzdt4j.server.common.base.Results;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * The type Config controller.
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2023 /11/13 22:18
 */
@RestController
@AllArgsConstructor
@RequestMapping(Constants.CONFIG_CONTROLLER_PATH)
public class ConfigController {

    private final ConfigService configService;

    private final ConfigModificationVerifyServiceChoose configModificationVerifyServiceChoose;

    @GetMapping
    public Result<ConfigInfoBase> detailConfigInfo(@RequestParam("tpId") String tpId,
                                                   @RequestParam("itemId") String itemId,
                                                   @RequestParam("namespace") String namespace,
                                                   @RequestParam(value = "instanceId", required = false) String instanceId) {
        ConfigAllInfo configAllInfo = configService.findConfigRecentInfo(tpId, itemId, namespace, instanceId);
        return Results.success(configAllInfo);
    }

    @PostMapping
    public Result<Boolean> publishConfig(@RequestParam(value = "identify", required = false) String identify,
                                         @RequestBody ConfigAllInfo config) {
        if (UserContext.getUserRole().equals("ROLE_ADMIN")) {
            configService.insertOrUpdate(identify, true, config);
        } else {
            final ConfigModifySaveReqDTO modifySaveReqDTO = BeanUtil.convert(config, ConfigModifySaveReqDTO.class);
            modifySaveReqDTO.setCorePoolSize(config.getCoreSize());
            modifySaveReqDTO.setMaximumPoolSize(config.getMaxSize());
            modifySaveReqDTO.setModifyUser(UserContext.getUserName());
            modifySaveReqDTO.setModifyAll(StrUtil.isEmpty(identify));
            modifySaveReqDTO.setIdentify(identify);
            modifySaveReqDTO.setType(ConfigModifyTypeConstants.THREAD_POOL_MANAGER);
            configModificationVerifyServiceChoose.choose(modifySaveReqDTO.getType()).saveConfigModifyApplication(modifySaveReqDTO);
        }
        return Results.success(Boolean.TRUE);
    }
}
